package com.androidme.app.framework.drawable;

import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;

public class Gauge extends Drawable {

    private Drawable mBar;
    private double mPercent;
    private int lastWidth = -1;

    private boolean isAlignRight;

    public Gauge(Drawable bar, double percent) {
        this(bar, percent, false);
    }

    public Gauge(Drawable bar, double percent, boolean isRight) {
        mBar = bar;
        mPercent = percent;
        isAlignRight = isRight;
    }

    private int getBarWidth() {
        if (mPercent == 0) {
            return 0;
        } else {
            int width = (int) (getBounds().width() * mPercent / 100);
            //Return the intrinsic width of the underlying drawable object.
            //Returns -1 if it has no intrinsic width, such as with a solid color
            int intrinsicWidth = mBar.getIntrinsicWidth();
            return Math.max(width, intrinsicWidth);
        }
    }

    @Override
    public void draw(Canvas canvas) {
        if (lastWidth == -1) {
            lastWidth = getBarWidth();
            //todo:int height = getBounds().height();
            int height = mBar.getIntrinsicHeight();
            if (isAlignRight) {
                int width = getBounds().width();
                mBar.setBounds(width - lastWidth, 0, width, height + 2);
            } else {
                mBar.setBounds(0, 0, lastWidth, height + 2);
            }
        }
        mBar.draw(canvas);
    }

    @Override
    public int getIntrinsicHeight() {
        return mBar.getIntrinsicHeight();
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }

    @Override
    public void setAlpha(int alpha) {
        mBar.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        mBar.setColorFilter(cf);
    }

}

